import axios, { AxiosError, AxiosResponse } from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css';
import { UserModel } from '@/modal/user';
import { constants } from '@/store/constant';
import { message as Msg } from 'antd'
import { notification, } from 'antd';
const rootUserStore = JSON.parse(localStorage.getItem(constants.ROOT_USER_STORE) || '{}') as UserModel
const instance = axios.create({
  // baseURL: import.meta.env.VITE_BASE_API,//跨域问题  后端没解决这里要打开  vite.configt.ts 要去设置server proxy
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 20000, //设置超时
  responseType: 'json',
  headers: {
    ['Content-type']: 'application/json',
    ['Authorizition']: rootUserStore.token
  }
})


const start = () => {
  NProgress.start();
}

const end = () => {
  NProgress.done();
}

//设置请求拦截器
instance.interceptors.request.use(config => {
  start()
  return config
}, error => {
  end()
  return Promise.reject(error)
})

//设置响应拦截器
instance.interceptors.response.use(res => {
  end()
  const { code, message } = res.data
  if (code && code !== 200) {
    // Msg.warning(message)
    notification.warning({ message })

  }
  return { data: res.data } as AxiosResponse

}, (error: AxiosError) => {
  end()
  Msg.error(error.message)
  return Promise.reject(error)
})

export default instance
